package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.ResultMap;
import cn.lijinquan.p2p.entites.User;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import com.lijinquan.springcloud.service.MailService;
import com.lijinquan.springcloud.utils.MSMUtils;
import com.lijinquan.springcloud.utils.SecretUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lijinquan on 2019/9/15.
 */

@RestController
public class VerificationControllerConsumer {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String REST_URL_PREFIX = "http://P2P-WEB/";
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MailService mailService;


    /**
     * 获取手机验证码
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/verification/sendMessage")
    public ResultMap<String> getPhoneCode(HttpServletRequest request) throws UnsupportedEncodingException {
        ResultMap<String> rm = new ResultMap<>();
        String phone = request.getParameter("phone");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setBody(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        if (phone == null || phone.equals("")) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        logger.info("======> SendMassage  phone = " + phone + " for get code");
        String ranNum = RandomStringUtils.randomNumeric(4);

        Map<String, Object> map = new HashMap<>();
        map.put("key", phone);
        map.put("value", ranNum);
        Boolean b = restTemplate.postForObject(REST_URL_PREFIX + "redis/set", map, Boolean.class);
        if (!b) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        //String content = "您好，您的验证码是 "+ranNum+"【lijinquan】";
        //String result = MSMUtils.SendSms(phone, content);
        // rm.setBody(result);
        return rm;


    }


    /**
     * 安全验证手机
     *
     * @param request
     * @return
     */
    @RequestMapping("/user/addPhone")
    public ResultMap<String> addPhone(HttpServletRequest request) {
        ResultMap<String> rm = new ResultMap<>();
        String phone = request.getParameter("phone");
        String phoneCode = request.getParameter("phoneCode");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        if (phone == null || phone.equals("") || phoneCode == null || phoneCode.equals("")) {
            rm.setStatus(FrontStatusConstants.NULL_OF_MOBILE_NO); //
            return rm;
        }
        String s = restTemplate.getForObject(REST_URL_PREFIX + "redeis/getValueByKey/" + phone, String.class);
        if (s == null || s.equals("") || !s.equals(phoneCode)) {
            rm.setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD);// 验证码不正确
            return rm;
        }
        User u = restTemplate.getForObject(REST_URL_PREFIX + "/user/getUserById/" + tokenmap.get("id"), User.class);
        if (u == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        u.setPhoneStatus(1);
        u.setPhone(phone);
        Boolean aBoolean = restTemplate.postForObject(REST_URL_PREFIX + "/user/modifyUser", u, Boolean.class);
        rm.setStatus(aBoolean ? FrontStatusConstants.SUCCESS : FrontStatusConstants.BREAK_DOWN);
        return rm;
    }


    /**
     * 实名认证
     * @param request
     * @return
     */
    @RequestMapping("/verification/verifiRealName")
    public ResultMap<String> verifiRealName(HttpServletRequest request) {
        ResultMap<String> rm = new ResultMap<>();
        String realName = request.getParameter("realName");
        String identity = request.getParameter("identity");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        User user = restTemplate.getForObject(REST_URL_PREFIX + "/user/getUserById/" + tokenmap.get("id"), User.class);
        if (user == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        user.setRealName(realName);
        user.setInviteid(identity);
        user.setPhoneStatus(1);
        Boolean aBoolean = restTemplate.postForObject(REST_URL_PREFIX + "/user/modifyUser", user, Boolean.class);
        rm.setStatus(aBoolean ? FrontStatusConstants.SUCCESS : FrontStatusConstants.BREAK_DOWN);
        return rm;
    }

    /**
     * 邮箱认证
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/emailAuth/auth")
    public ResultMap<String> emailAuth(HttpServletRequest request) throws Exception {
        ResultMap<String> rm = new ResultMap<>();
        String userId = request.getParameter("userId");
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String token = request.getHeader("token");

        boolean checkEmail = MSMUtils.checkEmail(email);
        if (!checkEmail) {//是正确的邮箱地址
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            rm.setBody("邮箱地址不正确！");
        }
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        User user = restTemplate.getForObject(REST_URL_PREFIX + "/user/getUserById/" + tokenmap.get("id"), User.class);
        if (user == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }

        if (user.getEmail() != null && user.getEmail().equals(email) && user.getEmailStatus() == 1) {
            rm.setStatus("177");
            return rm;
        }
//        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);

        String enc = SecretUtil.encrypt(userId);// 加密用户Id

        String message = MSMUtils.getMailCapacity(email, enc, username);
//        String message = "xxx平台邮箱安全认证：" + checkCode;

        try {
            mailService.sendSimpleMail(email, "平台账号邮箱安全验证", message);
            user.setEmail(email);
            Boolean aBoolean = restTemplate.postForObject(REST_URL_PREFIX + "/user/modifyUser", user, Boolean.class);

        } catch (Exception e) {
            logger.error("------> EmailAuth fail !");
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }

        return rm;
    }


    /**
     * 邮箱激活
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("emailAuth/emailactivation")
    public void activEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        ResultMap<String> rm = new ResultMap<>();
        String us = request.getParameter("us");

        try {
            String decode = SecretUtil.decode(us);
            User user = restTemplate.getForObject(REST_URL_PREFIX + "/user/getUserById/" + decode, User.class);
            if(user!=null && user.getEmailStatus()==1){
                response.getWriter().write("您已经通过了邮箱认证，请确认！");
            }
            user.setEmailStatus(1);
            Boolean aBoolean = restTemplate.postForObject(REST_URL_PREFIX + "/user/modifyUser", user, Boolean.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("邮箱认证失败！");
        }
        response.getWriter().write("邮箱认证成功！");
    }


    /**
     * 银行卡绑定  校验验证码
     */
    @RequestMapping("/verification/validateSMS")
    public ResultMap<String> validateSMS(HttpServletRequest request) {
        ResultMap<String> rm = new ResultMap<>();
        String phone = request.getParameter("phone"); //手机号
        String code = request.getParameter("code"); // 手机验证码
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            rm.setBody(null);
            rm.setCode("Fail");
            rm.setStatus(FrontStatusConstants.NULL_OF_VALIDATE_CARD); // 验证码为空
        }
        String s = restTemplate.getForObject(REST_URL_PREFIX + "redeis/getValueByKey/" + phone, String.class);
        if (s == null || s.equals("") || !s.equals(code)) {
            rm.setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD);// 验证码不正确
            return rm;
        } else {
            logger.info("======> Code Validate is true!");
        }

        return rm;
    }



    /**
     * activemq 消息队列
     * @param request
     * @return
     */
    @RequestMapping("emailAuth/activeSend")
    public ResultMap<String> activeSend(HttpServletRequest request){

        String send = request.getParameter("send");

        Boolean aBoolean = restTemplate.getForObject(REST_URL_PREFIX + "/active/send/"+send, Boolean.class);

        return null;

    }

}
